package com.greyu.ysj.controller;


import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.greyu.ysj.config.Constants;
import com.greyu.ysj.entity.CbtAsset;
import com.greyu.ysj.entity.CbtAutoExchange;
import com.greyu.ysj.entity.CbtCoinPrice;
import com.greyu.ysj.entity.CbtCoininfo;
import com.greyu.ysj.entity.CbtConstant;
import com.greyu.ysj.entity.CbtDraw;
import com.greyu.ysj.entity.CbtIncome;
import com.greyu.ysj.entity.CbtInvest;
import com.greyu.ysj.entity.CbtInvitedIncome;
import com.greyu.ysj.entity.CbtPayLog;
import com.greyu.ysj.entity.CbtRecharge;
import com.greyu.ysj.entity.User;
import com.greyu.ysj.mapper.CbtInvestMapper;
import com.greyu.ysj.model.ResultModel;
import com.greyu.ysj.service.CbtAssetService;
import com.greyu.ysj.service.CbtAutoExchangeService;
import com.greyu.ysj.service.CbtCoinInfoService;
import com.greyu.ysj.service.CbtCoinPriceService;
import com.greyu.ysj.service.CbtConstantService;
import com.greyu.ysj.service.CbtDrawService;
import com.greyu.ysj.service.CbtIncomeService;
import com.greyu.ysj.service.CbtInvestService;
import com.greyu.ysj.service.CbtInvitedIncomeService;
import com.greyu.ysj.service.CbtMinerRatioService;
import com.greyu.ysj.service.CbtPayLogService;
import com.greyu.ysj.service.CbtRatioService;
import com.greyu.ysj.service.CbtRechargeService;
import com.greyu.ysj.service.UserService;
import com.greyu.ysj.utils.NodeItem;
import com.greyu.ysj.utils.WalletAccount;
import com.greyu.ysj.utils.WalletProcess;




/*
 * 结算定时器任务
 */
@Component
@Service
@RestController
@RequestMapping("/income")

public class SettleTask {
	
	@Autowired
	private  CbtIncomeService cbtIncomeService;
	@Autowired
	private  CbtRatioService cbtRatioService;
	@Autowired
	private CbtInvestService cbtInvestService;
	@Autowired
	private CbtPayLogService cbtPayLogService;
	@Autowired
	private CbtAssetService cbtAssetService;
	@Autowired
	private CbtDrawService cbtDrawService;
	@Autowired
	private CbtCoinInfoService cbtCoinInfoService;
	@Autowired
	private CbtConstantService cbtConstantService;
	@Autowired
	private UserService userService;
	@Autowired
	private CbtInvitedIncomeService cbtInvitedIncomeService;
	@Autowired 
	private CbtMinerRatioService cbtMinerRatioService;
	@Autowired
	private CbtCoinPriceService cbtCoinPriceService;
	@Autowired
	private CbtInvestMapper cbtInvestMapper;
	@Autowired
	private CbtRechargeService cbtRechargeService;
	
	@Autowired
	private CbtAutoExchangeService cbtAutoExchangeService;
	/**
	 * 存单的利息
	 */
	private void StaticIncomeProcess_Ext() {
		System.out.println("====StaticIncomeProcess_Ext====");
		List<User> userIdList=this.userService.selectAllUsers(new User());
		if (userIdList.size()<=0) {
			return;
		}
		for(User user : userIdList) {
			//推荐的两代的用户userId
			int TmpuserId=user.getUserId();
			List<CbtInvest> cbtInvestList = this.cbtInvestMapper.selectByuserId(TmpuserId);
			if (cbtInvestList.size() <=0) {
				continue;
			}
			for (CbtInvest invest:cbtInvestList) {
				//用户ID
				int userId=invest.getUserId();
				//存单ID
				int investId=invest.getId();
				//投资时间
				//获取投资数额
				double investAmoount=invest.getInvestAmount();		
				int userStar = this.userService.getUserStart(userId);
				double minerRatio = this.cbtMinerRatioService.getRatioByLevel(userStar);
				
				double investIncome = 0.0;
				CbtIncome cbtIncomePer = invest.getCbtIncome();
				System.out.println("cbtIncomePer" + cbtIncomePer);
				if (cbtIncomePer !=null && cbtIncomePer.getIncome() !=null) {
					investIncome = cbtIncomePer.getIncome();
				}
				if ( investIncome >= investAmoount) {
					continue;
				}
				//更新记录
				System.out.println("investId=>"+investId);
				//计算收益
				double income = (investAmoount - investIncome)*minerRatio;
				//更新数据库表
				CbtIncome cbtIncome = new CbtIncome();
				cbtIncome.setUserId(userId);
				cbtIncome.setInvestId(investId);
				cbtIncome.setIncome(income);
				cbtIncome.setDate(new Date());
				this.cbtIncomeService.save(cbtIncome);
			}
			
		}
		System.out.println("====rewardProcess END====");
	}
	
//	private void StaticIncomeProcess() {
//		System.out.println("====StaticIncomeProcess====");
//		/**结算用户存单收益*/
//		List<CbtInvest> investList = this.cbtInvestService.getAllInvestList();
//		if (investList.size() < 1) {
//			return;
//		}
//		for (CbtInvest invest:investList) {
//			//用户ID
//			int userId=invest.getUserId();
//			//存单ID
//			int investId=invest.getId();
//			//投资时间
//			//获取投资数额
//			double investAmoount=invest.getInvestAmount();		
//			int userStar = this.userService.getUserStart(userId);
//			double minerRatio = this.cbtMinerRatioService.getRatioByLevel(userStar);
//			
//			double investIncome = 0.0;
//			CbtIncome cbtIncomePer = invest.getCbtIncome();
//			System.out.println("cbtIncomePer" + cbtIncomePer);
//			if (cbtIncomePer !=null && cbtIncomePer.getIncome() !=null) {
//				investIncome = cbtIncomePer.getIncome();
//			}
//			if ( investIncome >= investAmoount) {
//				continue;
//			}
//			//更新记录
//			System.out.println("investId=>"+investId);
//			//计算收益
//			double income = (investAmoount - investIncome)*minerRatio;
//			//更新数据库表
//			CbtIncome cbtIncome = new CbtIncome();
//			cbtIncome.setUserId(userId);
//			cbtIncome.setInvestId(investId);
//			cbtIncome.setIncome(income);
//			cbtIncome.setDate(new Date());
//			this.cbtIncomeService.save(cbtIncome);
//		}
//		System.out.println("====StaticIncomeProcess END====");
//	}
//	
	/**
	 * 用户提现
	 */
	private void withDrawCBTProcess() {
		//获取任务的所有信息
		CbtAutoExchange cbtAutoExchange=new CbtAutoExchange();
		cbtAutoExchange.setStatus(2);
		List<CbtAutoExchange>list=this.cbtAutoExchangeService.selectAll(cbtAutoExchange);
		for (CbtAutoExchange draw : list) {
			if (draw == null) {
				continue;
			}
			String tmpHash = draw.getDrawHash();
			//判断hash是否交易成功
			WalletProcess walletProcess = new WalletProcess();
			WalletAccount walletAccount = null;
			if (draw.getCoinId()==10000011) {
				 walletAccount = walletProcess.DoCheckTx(tmpHash);
			}else if(draw.getCoinId()==10000016)  {
				 walletAccount = walletProcess.DoDFCCheckTx(tmpHash);
			}else{
				walletAccount = walletProcess.DoUSDTCheckTx(tmpHash);
			}
			if (walletAccount.getResult()) {
				int hashStatus = walletAccount.getHashStatus();
				switch (hashStatus) {
				//成功
				case Constants.TRANSFER_HASH_STATUS_SUCESS:
					//支付成功
					draw.setStatus(1);
					int drawId=draw.getId();
					this.cbtAutoExchangeService.updateCbtAutoExchange(drawId, draw);
					//更新日志
//					CbtPayLog cbtPayLog=this.cbtPayLogService.selectByDrawId(drawId);
//					int payId=cbtPayLog.getId();
//					cbtPayLog.setFlag(1);
//					cbtPayLog.setPayDate(new Date());
//					this.cbtPayLogService.updateCbtPayLog(payId, cbtPayLog);
					//
//					//更新用户充值表
//					CbtCoininfo cbtCoininfo=cbtCoinInfoService.selectCoinInfoBycoinSymbol("AKB");
//					CbtRecharge cbtRecharge=new CbtRecharge();
//					cbtRecharge.setCoinId(cbtCoininfo.getCoinId());
//					cbtRecharge.setUserId(cbtPayLog.getUserId());
//					//用户币减少
//					cbtRecharge.setAmount(-cbtPayLog.getCbtAmount());
//					cbtRecharge.setRechargeDate(new Date());
//					cbtRecharge.setBlockNum(0);
//					this.cbtRechargeService.save(cbtRecharge);
					
					break;
				case Constants.TRANSFER_HASH_STATUS_PENDING:
					continue;
				case Constants.TRANSFER_HASH_STATUS_FAIL:
					//支付失败
					draw.setStatus(0);
					int id=draw.getId();
					this.cbtAutoExchangeService.updateCbtAutoExchange(id, draw);
					//更新日志
//					CbtPayLog payLog=this.cbtPayLogService.selectByDrawId(id);
//					int payId1=payLog.getId();
//					payLog.setFlag(0);
//					this.cbtPayLogService.updateCbtPayLog(payId1, payLog);
					
					//对用户资产进行回退
					CbtCoininfo cbtCoininfo=cbtCoinInfoService.selectCoinInfoBycoinSymbol("AKB");
					CbtRecharge cbtRecharge=new CbtRecharge();
					cbtRecharge.setCoinId(cbtCoininfo.getCoinId());
					cbtRecharge.setUserId(draw.getUserId());
					//用户币减少
					cbtRecharge.setAmount(draw.getAmount());
					cbtRecharge.setRechargeDate(new Date());
					cbtRecharge.setBlockNum(0);
					this.cbtRechargeService.save(cbtRecharge);
					
//					int userId=draw.getUserId();
//					double amount=draw.getAmount();
//					CbtAsset cbtAsset=this.cbtAssetService.selectAssetByuserId(userId);
//					cbtAsset.setAsset(cbtAsset.getAsset()+amount);
//					this.cbtAssetService.updateAsset(userId, cbtAsset);
					break;
				default:
					break;
				}
			}
		}
		return;
	}
	
	/**
	 * 奖励推荐用户
	 */
	private void rewardProcess() {
		System.out.println("====rewardProcess====");
		/**用户投资成功,给予推荐人奖励*/
		CbtConstant cbtConstant1=this.cbtConstantService.selectConstantById(1);
		CbtConstant cbtConstant2=this.cbtConstantService.selectConstantById(2);
		String rate1=cbtConstant1.getString2();
		double rewardRate1=Double.parseDouble(rate1)/100;
		CbtInvitedIncome cbtInvitedIncome =new CbtInvitedIncome();
		double amount=0.0;
		//获取所有用户的userId
		List<User>userIdList=this.userService.selectAllUsers(new User());
		for(User user : userIdList) {
			//推荐的两代的用户userId
			int userId=user.getUserId();
			
			/**2019-3-21用户没有投资不能获取推荐收益*/
			int total=this.cbtInvestService.countInvestsByuserId(userId);
			if(total < 1) {
				continue;
			}
			
			List<NodeItem> list=this.userService.getTwoGeneration(userId);
			if(list.size() < 1) {
				continue;
			}
			for(NodeItem nodeItem : list) {
				int childId=nodeItem.getUserId();
				int level=nodeItem.getLevelIndex();
				if (level != 1) {
					//目前仅仅计算直接推荐收益
					continue;
				}
				/**2019-3-21推荐收益一次性返还*/
				List<CbtInvest> investList=this.cbtInvestService.getYesterdayInvestByuserId(childId);
				if(investList.size() < 1) {
					continue;
				}
				//计算存单总的收益
				cbtInvitedIncome.setUserId(userId);
				cbtInvitedIncome.setRegisterNo(childId);
				cbtInvitedIncome.setCreateDate(new Date());
				for(CbtInvest invest : investList) {
					//存单ID
					int investId=invest.getId();
					//投资时间
					Date date=invest.getInvestDate();
					System.out.println("getInvestDate=>"+date);
					//获取投资数额
					double investAmoount=invest.getInvestAmount();
					cbtInvitedIncome.setInvestId(investId);
					if(level == 1) {
						amount=investAmoount/invest.getRatio()*rewardRate1;
						cbtInvitedIncome.setAmount(amount);
						cbtInvitedIncome.setFlag(1);
					}

					this.cbtInvitedIncomeService.save(cbtInvitedIncome);
				}
			}
		}
		System.out.println("====rewardProcess END====");
	}
		
	/***
	 * 暂时关闭
	 */
	@Scheduled(cron = "0 0 0 * * ?")
    public void IncomeProcessTask() {
        //System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "    " + Thread.currentThread().getName() + "    任务一启动");
		try {
			StaticIncomeProcess_Ext();
			Thread.sleep(1000);
//			rewardProcess();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
    }
	@Scheduled(cron = "*/30 * * * * ?")
    public void TransferProcessTask() {
        try {
        	withDrawCBTProcess();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }//任务耗时30秒
    }
	
	
	
	@PostMapping(value = "/incomeProcess")
	//@Authorization
	public ResponseEntity<ResultModel> incomeProcess() {
		try {
			StaticIncomeProcess_Ext();
		} catch (Exception e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", true);
		System.out.println(jsonObject);
		return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);		
	}
//	@PostMapping(value = "/rewardProcess")
//	//@Authorization
//	public ResponseEntity<ResultModel> rewardProcessTask() {
//		try {
//			rewardProcess();
//		} catch (Exception e) {
//			System.out.println(e.getMessage());
//			e.printStackTrace();
//		}
//		JSONObject jsonObject = new JSONObject();
//		jsonObject.put("result", true);
//		System.out.println(jsonObject);
//		return new ResponseEntity<>(ResultModel.ok(jsonObject), HttpStatus.OK);		
//	}
	
	
}
	
				
	
	


